const Router = require("breeze-web-router") ,
    Ret = require("./Ret")

/**
 *  
 */
class BaseAction{

    constructor( path ){
        this.root = path != "" ? "/" + path : path 
        this.route = new Router() 
        this.router = this.route.create( this.root )
        this._Route = {}
    }
    
    _route( key , value ){
        if( key ){
            if( value ){
                if( this._Route[ key ] ){
                    throw new Error("重复路由, " + key )
                }
                this._Route[ key ] = value 
            }
            return this._Route[ key ]
        }
        return this._Route
    }

    koa() {
        return this.route.Koa()
    }

    request( method , cfg , fn ){
        method = method.toUpperCase()
        const path = cfg.path 
        if( method == "GET")
            this.router.get( path , fn )
        else if( method == "POST")
            this.router.post( path , fn )
        else throw new Error("无法识别的Request Method")

        //存储配置
        const key = method + " " + this.root + path
        //为了更好的扩展性
        this._route( key , cfg )
    }

    get( cfg , fn ){
        this.request("GET" , cfg , fn )
    }

    post( cfg , fn ){
        this.request( "POST" , cfg , fn )
    }

    /**
     *  快速构建返回包
     * @param {*} data
     */
    succ( data ) {
        return Ret.succ(  data )
    }

    err( code , info , msg ) {
        return Ret.err( code , info , msg )
    }

}
    
module.exports = BaseAction